package svc

import (
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/config"
	"gitee.com/unitedrhino/share/caches"
	"gitee.com/unitedrhino/share/def"
	"gitee.com/unitedrhino/share/utils"
	"gitee.com/unitedrhino/things/sdk/protocol"
	"gitee.com/unitedrhino/things/service/dmsvr/pb/dm"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/kv"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config   config.Config
	Protocol *protocol.MqttProtocol
	Store    kv.Store
	NodeID   int64
}

func NewServiceContext(c config.Config) *ServiceContext {
	caches.InitStore(c.CacheRedis)
	nodeID := utils.GetNodeID(c.CacheRedis, c.Name)

	Protocol, err := protocol.NewMqttProtocol(c.Event, &dm.ProtocolInfo{
		Name:          "物美协议",
		Code:          def.ProtocolCodeWumei,
		TransProtocol: def.ProtocolMqtt,
		EtcdKey:       c.Etcd.Key,
	}, &protocol.CoreProtocolConf{
		ServerName: c.Name,
		NodeID:     nodeID,
		DmClient:   zrpc.MustNewClient(c.DmRpc.Conf),
		TimedM:     zrpc.MustNewClient(c.TimedJobRpc.Conf),
	}, c.DevLink)
	logx.Must(err)

	return &ServiceContext{
		Config:   c,
		Store:    kv.NewStore(c.CacheRedis),
		Protocol: Protocol,
		NodeID:   nodeID,
	}
}
